/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-07-05 19:37:03
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { Modal } from 'antd';
import {
  ADD_GROUP_PLAN_PROPS,
  SET_EXPANDED_KEYS,
  SET_GROUP_PLAN_LIST,
  SET_SELECTED_KEYS,
  SET_TREE_LIST
} from '../constants';
import { FolderTreeReducer } from '../reducers/FolderTreeReducer';
import {
  deleteFolderTreeNodeById,
  editTreeNode,
  fetchChildTreeNode,
  fetchFondNodeByUnitId
} from '@/api/floderTree';
import { appState } from '@/store/mobx';
import { addTreeNodeById, deleteTreeNodeById, replaceTreeNode } from '@/utils';

const initialState = {
  // 选中的目录树节点ID
  selectNodeId: 0,

  // 树数据
  treeData: [],
  // 扁平化后的树
  flatTreeList: [],
  // 目录树展开的key
  expandedKeys: [],
  // 目录树选中的key
  selectedKeys: [],
  // 分组方案穿梭框选中项目列表
  groupTargetList: [],

  // -------- 字典 --------
  // 节点类型列表
  nodeTypeList: [
    { id: 1, name: '单位节点', value: 'UNIT' },
    { id: 2, name: '全宗节点', value: 'FOND' },
    { id: 3, name: '档案类型', value: 'AT' },
    { id: 4, name: '描述性节点', value: 'DESC' },
    { id: 5, name: '数据节点', value: 'DATA' },
    { id: 6, name: '分组节点', value: 'GROUP' }
  ]
};

const FolderTreeContext = createContext();

const FolderTreeContextProvider = (props) => {
  const [state, dispatch] = useReducer(FolderTreeReducer, initialState);

  const actions = {
    /**
     * @description: 获取目录树根节点
     * 请求到单位节点后如果有信息，则根据第一条节点id请求档案类型节点
     * 档案类型节点有信息，自动选中第一个档案类型
     * @param {*} unitId 单位ID
     */
    fetchRootNode(unitId) {
      return new Promise((resolve, reject) => {
        fetchFondNodeByUnitId(unitId).then((res) => {
          const { data } = res;
          if (data?.length > 0) {
            fetchChildTreeNode(data[0].id).then((reslove) => {
              const subData = reslove.data;
              const treeData = addTreeNodeById(
                data,
                data[0].id,
                subData.map((item) => ({
                  ...item,
                  isLeaf: item.leafNode
                }))
              );
              dispatch({ type: SET_TREE_LIST, data: treeData });
              if (subData?.length > 0) {
                const rootNode = data[0];
                const subNode = subData[0];
                const levelList = subNode.appContext ? JSON.parse(subNode.appContext) : [];
                const levelItem = levelList?.[0] || {};
                const atItem = {
                  id: subNode.businessId,
                  atName: subNode.nodeName,
                  atCode: levelItem.atCode,
                  atType: levelItem.atType,
                  atLevel: levelItem.level,
                  levelList
                };
                resolve({
                  fondId: rootNode.businessId,
                  fondNodeId: rootNode.id,
                  nodeId: subNode.id,
                  atItem
                });
              } else {
                resolve(null);
              }
            });
          } else {
            dispatch({ type: SET_TREE_LIST, data });
            resolve(null);
          }
        });
      });
    },

    /**
     * @description: 设置目录树数据
     * @param {*} tree 目录树
     */
    setTreeData(tree) {
      dispatch({ type: SET_TREE_LIST, data: tree });
    },

    /**
     * @description: 设置目录树展开的key
     * @param {Key[]} keys 展开的key
     */
    setExpandedKeys(keys) {
      dispatch({ type: SET_EXPANDED_KEYS, data: keys });
    },

    /**
     * @description: 设置目录树选中的key
     * @param {Key[]} keys 选中的key
     */
    setSelectKeys(keys) {
      dispatch({ type: SET_SELECTED_KEYS, data: keys });
    },

    /**
     * @description: 编辑目录树节点
     * @param {*} params
     */
    editTreeNodeFunc(params) {
      return new Promise((resolve, reject) => {
        editTreeNode(params).then((res) => {
          const { data } = res;
          data.isLeaf = data.leafNode;
          const tree = replaceTreeNode(state.treeData, data.id, data);
          dispatch({ type: SET_TREE_LIST, data: tree });
          resolve(data);
        });
      });
    },

    /**
     * @description: 根据目录树ID删除对应节点
     * @param {*} id
     */
    deleteTreeNode(id) {
      Modal.confirm({
        title: '删除节点',
        content: '删除目录树节点将连同其下子节点一同删除，且不可恢复。',
        onOk() {
          deleteFolderTreeNodeById(id).then((res) => {
            const { data } = res;
            console.log('delete node', data);
            const tree = deleteTreeNodeById(state.treeData, parseInt(data[0], 10));
            dispatch({ type: SET_TREE_LIST, data: tree });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @description: 节点类型列表转换为对象
     * @return {*} 转换为对象的节点类型
     */
    nodeTypeConst() {
      const type = {};
      state.nodeTypeList.forEach((item) => type[item.value] === item.id);
      return type;
    },

    /**
     * @description: 设置分组方案列表
     * @param {*} list 分组方案列表
     */
    setGroupPlanList(list) {
      dispatch({ type: SET_GROUP_PLAN_LIST, data: list });
    },

    /**
     * @description: 对某分组方案项目增加属性
     * @param {*} item 需要增加属性的项目
     * @param {*} propName 属性名
     * @param {*} data 增加的数据
     */
    groupPlanAddProp(item, propName, data) {
      dispatch({ type: ADD_GROUP_PLAN_PROPS, item, propName, data });
    }
  };

  useEffect(() => {}, []);

  return (
    <FolderTreeContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </FolderTreeContext.Provider>
  );
};

export const useFolderTreeContext = () => {
  return useContext(FolderTreeContext);
};

export { FolderTreeContext, FolderTreeContextProvider };
